<template>
    <div class="login">
        <div class="login-title">
            <div @click="change(1)" :class="loginOrRegister === 1 ? 'active' : ''"><span>登录</span></div>
            <div @click="change(0)" :class="loginOrRegister === 0 ? 'active' : ''"><span>注册</span></div>    
        </div>
        <el-form
            label-position="top"
            label-width="100px"
            ref="userRef"
            :model="user"
            :rules="rules"
            style="max-width: 250px">
            <el-form-item label="姓名：" prop="username">
                <el-input v-model="user.username" placeholder="请输入用户名" ref="usernameInput" @keyup.enter="this.$refs['pwdInput'].focus()"/>
            </el-form-item>
            <el-form-item label="密码：" prop="password">
                <el-input type="password" v-model="user.password" placeholder="请输入密码" ref="pwdInput" @keyup.enter="loginOrRegisterBtn('form')"/>
            </el-form-item>
            <p v-if="showError" style="color:red">{{error}}</p>
            <el-button type="primary" @click="loginOrRegisterBtn('former')" >{{loginbtn}}</el-button>
        </el-form>

        <span class="reset" @click="resetBtn">忘记密码？</span>

        <el-dialog
            v-model="dialogVisible"
            title="密码重置"
            width="40%"
            min-width="200px"
            margin-top="10px"
            margin-left="10px"
        >
            <el-form
                label-position="top"
                label-width="100px"
                :model="confirmUser"
                :rules="rules"
                style="max-width: 450px">
                <el-form-item label="姓名：" prop="username">
                    <el-input v-model="confirmUser.username" placeholder="请输入用户名" ref="confirmUsernameInput" @keyup.enter="this.$refs['confirmPwdInput'].focus()"/>
                </el-form-item>
                <el-form-item label="密码：" prop="password">
                    <el-input type="password" v-model="confirmUser.password" placeholder="请输入密码" ref="confirmPwdInput" @keyup.enter="this.$refs['confirmInput'].focus()"/>
                </el-form-item>
                <el-form-item label="确认密码：" prop="confirmPwd" :rules="{required:true,message:'请确认密码',trigger:'blur'}">
                    <el-input type="password" v-model="confirmUser.confirmPwd" placeholder="请确认密码" ref="confirmInput" @keyup.enter="resetPwd('form')"/>
                </el-form-item>
            </el-form>
            <p v-if="showError" style="color:red">{{error}}</p>
            <template #footer>
            <span class="dialog-footer">
                <el-button @click="dialogVisible = false">取消</el-button>
                <el-button type="primary" @click="resetPwd('former')">确定</el-button>
            </span>
            </template>
        </el-dialog>

    </div>
    
</template>

<script>
export default {
    name:"login",
    data(){
        return {
            user:{username:"",password:""},
            confirmUser:{username:"",password:"",confirmPwd:""},
            rules:{
                username:[
                    {required:true,message:"请输入用户名",trigger:"blur"}
                ],
                password:[
                    {required:true,message:"请输入密码",trigger:"blur"}
                ]
            },
            userList:[
                {username:"admin",password:"123"},
                {username:"11",password:"11"},
                {username:"22",password:"22"}
            ],
            showError:false,
            error:"",
            loginOrRegister:1,
            loginbtn:"登录",
            dialogVisible:false
        }
    },
    mounted(){
        this.firstInput();
    },
    methods:{
        firstInput(){
        this.$nextTick(() => {
            this.$refs.usernameInput.focus();
        })
    },
        // 点击注册，注册出现下划线，按钮为注册。点击登录，登录出现下划线，按钮为登录。
        change(i){
            if(i === 0){
                this.firstInput();
                this.loginOrRegister = 0;
                this.loginbtn = "注册"
            }else{
                this.firstInput();
                this.loginOrRegister = 1;
                this.loginbtn = "登录"
            }
        },
        // 点击登录按钮则查询数据，点击注册按钮则添加数据
        loginOrRegisterBtn(){
            if(this.loginOrRegister === 0){
                this.register()
            }else{
                this.login()
            }
        },
        // 注册
        register(){
            try{
                this.userList.forEach( u => {
                    if( u.username === this.user.username){
                        console.log('u.username === this.user.username',u.username,this.user.username)
                        this.showError = true;
                        this.error = "用户已存在，请重新注册";
                        this.firstInput();
                        this.$nextTick(() => {
                            this.$refs["userRef"].resetFields();
                        })
                        throw new Error("已找到，退出循环");
                    }
                })
            }catch(e){return};
            this.userList.push(this.user);
            this.showError = false;
            this.login();
            console.log("注册后",this.userList);
            this.$router.push("/")
        },
        // 登录查询验证
        login(){
            try{
                this.userList.forEach( u => {
                    if( u.username === this.user.username){
                        if(u.password === this.user.password){
                            localStorage.setItem('token',this.user.username)
                            this.$router.push("/");
                            console.log("登录后",this.userList);                           
                        }else{
                            this.showError = true;
                            this.error = "用户名或密码错误，请重新登录";
                            alert("用户名或密码错误，请重新登录");
                        }
                        throw new Error("找到用户");
                    }
                })
            }catch(e){return}
            this.$router.push("/login")
            this.showError = true;
            this.error = "用户名不存在，请注册";
            this.user = {username:"",password:""};
            this.change(0);
        },
        // 点击忘记密码的按钮，打开弹出框，对焦到第一个输入框
        resetBtn(){
            this.dialogVisible = true;
           setTimeout(() => {
                this.$refs.confirmUsernameInput.focus();
            },100)  
        },
        // 重置密码
        resetPwd(){
            if(this.confirmUser.confirmPwd !== this.confirmUser.password){
                this.showError = true;
                this.error = "两次输入密码不一致";
                this.confirmUser.confirmPwd = "";
                this.$refs.confirmInput.focus();
            }else{
                try{
                    this.userList.forEach( u => {
                        if( u.username === this.confirmUser.username){
                            u.password = this.confirmUser.password;
                            this.showError = false;
                            localStorage.setItem('token',this.confirmUser.username);
                            this.$router.push("/");
                            console.log("密码重置后",this.userList);
                            throw new Error("已更新，退出循环");
                        }
                    })
                }catch(e){return};
            }
        }
    }
}
</script>

<style>
.login {
    margin:80px auto;
    background-color: rgb(247, 241, 241);
    height:55%;
    width:30%;
    padding:0.8rem 1rem;
    display:grid;
    grid-template-rows: 1fr 5fr;
    place-items: center;
    border-radius: 2rem;
    min-width:260px;
}
.login .login-title{
    width:100%;
    font-size:1.5rem;
    display:flex;
    justify-content: space-around;
    margin-bottom:1rem;
}
.login .login-title div{
    margin-bottom:5px;
}
.login .login-title .active{
    border-bottom:3px solid #79bbff;
    width:12rem;
}
.el-form--default.el-form--label-top .el-form-item .el-form-item__label {
    margin-bottom: 8px;
    line-height: 30px;
    font-size: 18px;
    margin-bottom: 15px;
}
.el-input__inner {
    height: 40px;
    font-size: 18px;
}
.el-button > span {
    font-size: 18px;
}
.reset{
    font-size:12px;
    margin-right:5px;
    width:100%;
    text-align: right;
}
.reset:hover{
    cursor:pointer;
}
.el-dialog {
    --el-dialog-margin-top: 7vh;
}
</style>